package com.atguigu.shardingjdbcdemo.algorithm;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author zhaojiaxu
 * @date 2021/10/20 15:56
 **/
@Slf4j
public class DefaultRangeModuloAlgorithm implements RangeShardingAlgorithm<Long> {
    /**
     * 实现between and查询
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        log.info("collection:{}", JSON.toJSONString(collection));
        log.info("rangeShardingValue:{}", JSON.toJSONString(rangeShardingValue));

        Collection<String> collect = new ArrayList<>();

        // SQL: SELECT * FROM course(逻辑表) where user_id between 200 and 300;
        // 数据分表逻辑是余数偶数分配到course_1  奇数分配到course_2 所以只要是范围查询就查询所有表
        for (String coll : collect){
            if(coll.equals("course")){
                collect.add("course_1");
                collect.add("course_2");
            }
        }
        return collect;
    }
}

